package org.spring.springboot.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.springboot.domain.City;
import org.spring.springboot.service.CityService;
import org.spring.springboot.vo.CityVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * 城市 Controller 实现 Restful HTTP 服务
 * <p>
 * Created by 赵新国 on 07/02/2017.
 */
@Controller
@RequestMapping("/admin")
public class CityController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CityService cityService;

    @RequestMapping(value = "/api/city/toAdd", method = RequestMethod.GET)
    public String toAddCity(Model model) {
        return "city/cityAdd";
    }

    @RequestMapping(value = "/api/city/saveCity", method = RequestMethod.POST)
    public String saveCity(Model model, CityVo cityVo) {
        City city = new City();
        BeanUtils.copyProperties(cityVo, city);
        cityService.saveCity(city);
        return "redirect:" + "/api/city";
    }

    @RequestMapping(value = "/api/city/{id}", method = RequestMethod.GET)
    public String findOneCity(Model model, @PathVariable("id") Long id) {
        model.addAttribute("city", cityService.findCityById(id));
        return "city/cityEdit";
    }

    @RequestMapping(value = "/api/city/delete/{id}", method = RequestMethod.GET)
    public String deleteOneCity(Model model, @PathVariable("id") Long id) {
        City city = cityService.findCityById(id);
        if(city != null) {
            cityService.deleteCity(id);
        }
        return "redirect:" + "/api/city";
    }

    @RequestMapping(value = "/api/city/editCity", method = RequestMethod.POST)
    public String editCity(Model model, CityVo cityVo) {
        City city = new City();
        BeanUtils.copyProperties(cityVo, city);
        cityService.updateCity(city);
        return "redirect:" + "/api/city";
    }

    @RequestMapping(value = "/api/city", method = RequestMethod.GET)
    public String findAllCity(Model model) {
        List<City> cityList = cityService.findAllCity();
        logger.info("城市列表：" + cityList.toString());
        model.addAttribute("cityList",cityList);
        return "city/cityList";
    }



}
